<template>
	<view class="watermark-wrapper" :style="{'background-image': 'url('+ watermark +')'}">
		<slot></slot>
	</view>
</template>

<script>
	export default {
		name: "watermark-view",
		data() {
			return {
				watermark: ''
			};
		},
		props: {
			image: {
				type: String,
				default: ''
			},
			text: {
				type: String,
				default: 'lbdev'
			}
		},
		mounted() {
			if (this.image) {
				this.watermark = this.image
			} else {
				this.createWatermark(this.text)
			}
		},
		watch: {
			image(newVal) {
				if (newVal) {
					this.watermark = newVal
				} else {
					this.createWatermark(newVal)
				}
			},
			text(newVal) {
				this.createWatermark(newVal || '')
			}
		},
		methods: {
			createWatermark(text) {
				const svgStr =
					`<svg xmlns="http://www.w3.org/2000/svg" width="120px" height="80px">
				      <text x="0px" y="30px" dy="16px"
				      text-anchor="start"
				      stroke="#000"
				      stroke-opacity="0.1"
				      fill="none"
				      transform="rotate(-20)"
				      font-weight="100"
				      font-size="16">${text}</text>
				    </svg>`;
				this.watermark = `data:image/svg+xml;base64,${uni.arrayBufferToBase64(this.strToBuffer(decodeURIComponent(encodeURIComponent(svgStr))))}`;
			},
			strToBuffer(str) {
				var bytes = new Array();
				var len, c;
				len = str.length;
				for (var i = 0; i < len; i++) {
					c = str.charCodeAt(i);
					if (c >= 0x010000 && c <= 0x10FFFF) {
						bytes.push(((c >> 18) & 0x07) | 0xF0);
						bytes.push(((c >> 12) & 0x3F) | 0x80);
						bytes.push(((c >> 6) & 0x3F) | 0x80);
						bytes.push((c & 0x3F) | 0x80);
					} else if (c >= 0x000800 && c <= 0x00FFFF) {
						bytes.push(((c >> 12) & 0x0F) | 0xE0);
						bytes.push(((c >> 6) & 0x3F) | 0x80);
						bytes.push((c & 0x3F) | 0x80);
					} else if (c >= 0x000080 && c <= 0x0007FF) {
						bytes.push(((c >> 6) & 0x1F) | 0xC0);
						bytes.push((c & 0x3F) | 0x80);
					} else {
						bytes.push(c & 0xFF);
					}
				}
				let arrayBuffer = new Uint8Array(bytes).buffer;
				return arrayBuffer;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.watermark-wrapper {
		position: relative;
		height: 100%;
	}
</style>